package com.base.admin.Interceptor;

import cn.hutool.core.date.DateUtil;
import cn.hutool.jwt.JWT;
import cn.hutool.jwt.JWTUtil;
import cn.hutool.jwt.JWTValidator;
import cn.hutool.jwt.signers.JWTSignerUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.base.admin.constant.HttpStatusConstant;
import com.base.admin.constant.WebConstant;
import com.base.admin.context.GlobalContext;
import com.base.admin.entity.AdminUser;
import com.base.admin.service.AdminUserService;
import com.base.admin.util.ServletUtils;
import com.base.admin.util.StringUtils;
import com.base.admin.vo.ResultBean;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Arrays;
import java.util.List;

/**
 * 登录拦截器
 * @author rqq
 */

@Component
public class LoginInterceptor implements HandlerInterceptor {

    @Value("${token.key}")
    private String tokenKey;

    @Resource
    private AdminUserService adminUserService;

    /**
     * 免登录白名单
     */
    private final List<String> whiteList = Arrays.asList("/login");

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String uri = request.getRequestURI();
        if (whiteList.contains(uri)) {
            return true;
        }
        String token = request.getHeader(WebConstant.LOGIN_HEADER);
        if (StringUtils.isBlank(token)) {
            response.setStatus(HttpStatusConstant.NOT_LOGIN);
            ServletUtils.writeJson(ResultBean.error("请登录"), response);
            return false;
        }
        try {
            JWTValidator.of(token).validateAlgorithm(JWTSignerUtil.hs256(tokenKey.getBytes()));
        } catch (Exception ex) {
            response.setStatus(HttpStatusConstant.NOT_LOGIN);
            ServletUtils.writeJson(ResultBean.error("请登录"), response);
            return false;
        }
        try {
            JWTValidator.of(token).validateDate(DateUtil.date());
        }catch (Exception ex) {
            response.setStatus(HttpStatusConstant.NOT_LOGIN);
            ServletUtils.writeJson(ResultBean.error("登录信息过期，请重新登录"), response);
            return false;
        }
        final JWT jwt = JWTUtil.parseToken(token);
        String username = jwt.getPayload("uname").toString();
        LambdaQueryWrapper<AdminUser> adminUserWrapper = new LambdaQueryWrapper<>();
        adminUserWrapper.eq(AdminUser::getUsername, username);
        GlobalContext.set(adminUserService.getOne(adminUserWrapper));
        return true;
    }
}
